import { logoutApi } from '@/api/oauth'
import { getUserInfoApi, updatePasswordApi } from '@/api/user'
import { clearLoginInfo } from '@/utils'

// 用户基本信息
export default {
  namespaced: true,
  state: {
    id: 0,
    nickName: '',
    userName: '',
    headUrl: '',
    email: '',
    sex: 0,
    root: false
  },
  mutations: {
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NICKNAME: (state, nickName) => {
      state.nickName = nickName
    },
    SET_USERNAME: (state, userName) => {
      state.userName = userName
    },
    SET_HEADURL: (state, headUrl) => {
      state.headUrl = headUrl
    },
    SET_EMAIL: (state, email) => {
      state.email = email
    },
    SET_SEX: (state, sex) => {
      state.sex = sex
    },
    SET_ROOT: (state, root) => {
      state.root = root
    }
  },
  actions: {
    getUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfoApi().then(res => {
          let data = res.data
          commit('SET_ID', data.id)
          commit('SET_NICKNAME', data.nickName)
          commit('SET_USERNAME', data.userName)
          commit('SET_HEADURL', data.headUrl)
          commit('SET_EMAIL', data.email)
          commit('SET_SEX', data.sex)
          commit('SET_ROOT', data.root)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        logoutApi().then(res => {
          commit('SET_ID', '')
          commit('SET_NICKNAME', '')
          commit('SET_USERNAME', '')
          commit('SET_HEADURL', '')
          commit('SET_EMAIL', '')
          commit('SET_SEX', '')
          commit('SET_ROOT', '')
          clearLoginInfo()
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    updatePassword({ commit, state, dispatch }, dataForm) {
      return new Promise((resolve, reject) => {
        updatePasswordApi(dataForm).then(res => {
          commit('SET_ID', '')
          commit('SET_NICKNAME', '')
          commit('SET_USERNAME', '')
          commit('SET_HEADURL', '')
          commit('SET_EMAIL', '')
          commit('SET_SEX', '')
          commit('SET_ROOT', '')
          clearLoginInfo()
          dispatch('common/UpdateMainTabs', [], { root: true })
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
